﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace bookMaster.AssetSystem.Shell.Clases
{
    public class HashValues
    {
        private static byte[] seedValues = { 0x41, 0x6e, 0x64, 0x72, 0x65, 0x61, 0x20, 0x53, 0x6f, 0x66, 0x69, 0x61 };

        public static string CalculateHash(string text, Encoding enc, string hashType)
        {

            //Convert string to byte buffer:
            byte[] buffer = enc.GetBytes(text);

            //HashAlgorithm is IDisposable:
            using (HashAlgorithm hashAlgorithm =
              HashAlgorithm.Create(hashType))
            {

                byte[] hashBuffer =
                  hashAlgorithm.ComputeHash(buffer);

                byte[] combinedHash = new byte[hashBuffer.Length + seedValues.Length];
                seedValues.CopyTo(combinedHash, 0);
                hashBuffer.CopyTo(combinedHash, seedValues.Length);


                //Method a:
                //System.Text.StringBuilder sb =
                //  new System.Text.StringBuilder();
                //foreach (byte b in hashBuffer) {
                //  sb.Append(b.ToString("x2"));//'X2' for uppercase
                //}
                //return sb.ToString();

                //Method B: 
                //string hashString =
                //  BitConverter.ToString(hashBuffer);
                //The output looks like:
                //"19-E2-62-AE-3A-84-0D-72-1F-EF-32-C9-25-D1-A1-89-67-13-5F-58"
                //so you want to remove the hashes in most cases:
                //return hashString.Replace("-", "");

                //Method C: Homebrewed speed:
                //Convert 20byte buffer to string...
                return ConvertHexByteArrayToString(combinedHash);
            }
        }

        private static string ConvertHexByteArrayToString(byte[] buffer)
        {
            char[] result = new char[buffer.Length * 2];

            int i = 0;
            foreach (byte b in buffer)
            {
                result[i] = GetHexValue(b / 0x10);
                result[i + 1] = GetHexValue(b % 0x10);
                i += 2;
            }
            return new string(result, 0, result.Length);
        }

        private static char GetHexValue(int X)
        {
            return (char)((X < 10) ? (X + 0x30) : ((X - 10) + 0x41));
        }

    }
}
